<template>
  <div>
    <div class="top">
      <div style="float: right;">
        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          :disabled="listLoading"
          @click="handleAction('create', '添加账号')"
        >添加账号
        </el-button>
      </div>
      <div style="float: right;margin-right: 10px;">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
      </div>

      <div style="clear: both" />
    </div>

    <el-table
      v-loading.fullscreen.lock="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="其他信息">
              <span>{{ props.row.buy_info }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" label="登录服务器" prop="login_host" sortable="custom" />
      <el-table-column align="center" label="账号" prop="gmail" sortable="custom" />
      <el-table-column align="center" label="密码" prop="password" sortable="custom" />
      <el-table-column align="center" label="辅助邮箱" prop="recover_mail" sortable="custom" />
      <el-table-column align="center" label="电话" prop="phone" sortable="custom" />
      <el-table-column align="center" label="可发邮件" prop="sendable" sortable="custom">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.sendable"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="网站列表" prop="websites" sortable="custom" width="300">
        <template slot-scope="scope">
          <el-badge :value="scope.row.websites.length" class="item">
            <el-dropdown v-if="scope.row.websites.length" trigger="click">
              <span class="el-dropdown-link">
                {{ scope.row.websites[0].domain }}<i class="el-icon-caret-bottom el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item,index) in scope.row.websites" :key="index" class="clearfix">
                  <a :href="item.domain" target="_blank">{{ item.domain }}</a>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-badge>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="create_at" />
      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleShowSendTestMail(scope.row)">测试</el-button>
          <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">

        <el-form-item v-if="action !== 'delete'" label="邮箱账号">
          <el-input v-model="temp.gmail" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="邮箱密码">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="辅助邮箱">
          <el-input v-model="temp.recover_mail" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="电话">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="登录服务器">
          <el-input v-model="temp.login_host" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="其他信息">
          <el-input v-model="temp.buy_info" type="textarea" :row="3" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="可发邮件">
          <el-switch
            v-model="temp.sendable"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="enable">
          <el-switch
            v-model="temp.enable"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="关联网站">
          <el-select
            v-model="temp.websites"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="输入域名搜索网站"
            :remote-method="remoteSearchWebsite"
            :loading="remoteSearchWebsite_loading"
          >
            <el-option
              v-for="item in website_options"
              :key="item.id"
              :label="item.domain"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="项目">
          <el-select v-model="temp.project_id" placeholder="选择项目">
            <el-option v-for="item in this.projects" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      title="发送测试邮件"
      :width="width"
      :visible.sync="testMailDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="test_mail" label-position="left" label-width="120px">
        <el-form-item label="gmail">
          <el-input v-model="test_mail.gmail" />
        </el-form-item>
        <el-form-item label="收件箱">
          <el-input v-model="test_mail.receiver_email" />
        </el-form-item>
        <el-form-item label="subject">
          <el-input v-model="test_mail.subject" />
        </el-form-item>
        <el-form-item label="body">
          <el-input v-model="test_mail.body" type="textarea" :row="3" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="testMailDialogVisible = false">取 消</el-button>
        <el-button @click="testSendMail">发 送</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, SendMailByGmail } from '@/api/orders/googlegmailaccount'
import qs from 'qs'
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as GetWebsite } from '@/api/erp/elicink/website'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Gmailaccount',
  data() {
    return {
      testMailDialogVisible: false,
      test_mail: {
        subject: 'test',
        gmail: '',
        body: 'simple mail test',
        receiver_email: 'ruanbanyong@qq.com'
      },
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        gmail: '',
        password: '@Rby123654',
        recover_mail: '',
        websites: [4, 15],
        phone: '',
        login_host: '',
        buy_info: '',
        project_id: '',
        enable: true
      },
      width: '',
      projects: [],
      innerDialogVisible: false,
      website_options: [],
      remoteSearchWebsite_loading: false
    }
  },
  created() {
    this.handleFetchProjects()
  },
  methods: {
    setWebsiteOptions(v) {
      v.forEach(website => {
        GetWebsite(website).then(response => {
          this.website_options.push(response.data)
        })
      })
    },
    remoteSearchWebsite(query) {
      if (query !== '') {
        this.remoteSearchWebsite_loading = true
        GetWebsite(null, qs.stringify({
          kw: query,
          pagesize: 5,
          page: 1
        })).then(response => {
          this.website_options = response.data.data
          this.remoteSearchWebsite_loading = false
        })
      } else {
        this.website_options = []
        this.remoteSearchWebsite_loading = false
      }
    },
    resetTemp() {
      this.temp = {
        gmail: '',
        login_host: '',
        password: '@Rby123654',
        recover_mail: '',
        websites: [],
        phone: '',
        buy_info: '',
        project_id: '',
        enable: true
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    testSendMail() {
      SendMailByGmail(this.test_mail).then(response => {
        this.notify('send success')
        this.testMailDialogVisible = false
      })
    },
    handleShowSendTestMail(row) {
      this.test_mail.gmail = row.gmail
      this.testMailDialogVisible = true
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.gmail}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.gmail}`
          this.temp = Object.assign({}, row)
          this.website_options = this.temp.websites
          this.temp.websites = this.temp.websites.map(v => {
            return v.id
          })
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (_data.project_id === '') {
            alert('必须选择项目')
            return
          }
          if (!_data.gmail.length) {
            alert('必须填写邮箱账号')
            return
          }
          if (!_data.password.length) {
            alert('必须填写密码')
            return
          }
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeWebDialog', false)
    },
    handleFetchProjects() {
      GetProjects()
        .then(response => {
          this.projects = response.data.data
        })
        .catch(e => {
          console.log('error')
        })
    }
  }
}
</script>
